﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TGB.Core.Infrastructure;
using TGBTech.Core.Models.Models;
using TGBTech.Core.Models.Models.BaoCao.SoChiTietThanhToanKHModel;

namespace TGBTech.Core.Models.Services
{
    public class SoChiTietThanhToanKHService
    {
        public SoChiTietThanhToanKH createSoChiTietThanhToanKH(String makh, String taikhoanid, DateTime? ngaybatdau, DateTime? ngayketthuc) { 
           //init resultData
            SoChiTietThanhToanKH resultData = new SoChiTietThanhToanKH();
            resultData.MaKH = makh;
            resultData.TaiKhoanId = taikhoanid;
            resultData.NgayBatDau = ngaybatdau;
            resultData.NgayKetThuc = ngayketthuc;
            //check valid input
            if (ngayketthuc == null || ngaybatdau == null
                || ngaybatdau > ngayketthuc || makh == null || makh == ""
                || taikhoanid == null || taikhoanid == "") {
                    return resultData;
            }
            //init db
            using (TGBTechDb db = new TGBTechDb())
            {
                //search query with input
                var searchQuery = from e in db.Data
                                  where e.NgayCT >= ngaybatdau && e.NgayCT <= ngayketthuc
                                      && e.KhachHangId == makh
                                      && (e.TaiKhoanCoId.StartsWith(taikhoanid) || e.TaiKhoanNoId.StartsWith(taikhoanid))
                                  select e;
                //create list data from search query
                var listData = searchQuery.ToList();
                //loop to create record from data
                SoChiTietThanhToanKHModel model;
                foreach (var data in listData)
                { 
                    //create record
                    model = SoChiTietThanhToanKHFactory.createSoChiTietThanhToanKH(data, taikhoanid);
                    //add record to list
                    resultData.ListModel.Add(model);
                }
            }          

            return resultData;
        }
    }
}
